/*
@Desc : 自定义拦截器演示
@Version : 1.0.0
@Time : 2019/7/5 15:58 
@Author : hammercui
@File : customInterceptor
@Company: Sdbean
*/
package grpc

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"time"
)

//可用来处理权限校验等
//拦截器的作用类似于中间件，也是洋葱型
func customInterceptor() grpc.UnaryServerInterceptor{
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		// before server handler
		startTime := time.Now()
		// 调用方法
		fmt.Println("custom interceptor grpc func:",info.FullMethod)
		//caller := metadata.String(ctx, metadata.Caller)
		//if caller == "" {
		//	caller = "no_user"
		//}
		//var remoteIP string
		//if peerInfo, ok := peer.FromContext(ctx); ok {
		//	remoteIP = peerInfo.Addr.String()
		//}
		//var quota float64
		//if deadline, ok := ctx.Deadline(); ok {
		//	quota = time.Until(deadline).Seconds()
		//}

		// call server handler
		resp, err = handler(ctx, req) // NOTE: 以具体执行的handler为分界线！！！
		fmt.Println("custom interceptor grpc time:",time.Since(startTime))
		// after server handler
		return resp,err
	}
}